﻿#include"knn.h"
#include<QDebug>
void KNN::show()
{
    map<int, double>::iterator it;
    for (it = map_index_dis.begin(); it != map_index_dis.end(); it++)
    {
        cout << "index = " << it->first << "  value = " << it->second << endl;
    }


}
KNN::KNN()
{
    fin.open("f:\\smartC\\knn_function.txt", ios::in);
    if (!fin)
    {
        cout << "can nod load the file" << endl;;
        system("pause");
        exit(1);
    }
    for (int i = 0; i < maxRow; i++)
    {
        for (int j = 0; j < maxCol; j++)
        {
            fin >> dataSet[i][j];
        }
        fin >> labels[i];
    }
//	cout << "输入测试数据：";
//	for (int n = 0; n < maxCol; n++)
//	{
//		cin >> testData[n];
//	}
//	cout << endl;
    QSqlQueryModel *model=new QSqlQueryModel;
    QString sql;
    sql="select x,y from knn where name='function'";
    model->setQuery(sql);
    QModelIndex indexx,indexy;
    indexx=model->index(0,0);
    indexy=model->index(0,1);
    float x,y;
    x=indexx.data().toFloat();
    y=indexy.data().toFloat();
    testData[0]=x;
    testData[1]=y;
    cout << "输入 k 的值：";
    k=1;

}
double KNN::get_distance(double* dt1, double* dt2)
{
    double sum = 0;
    for (int i = 0; i < maxCol; i++)
    {
        sum += pow((dt1[i] - dt2[i]), 2);
    }
    return (sqrt(sum));
}
void KNN::get_all_distance()
{
    double distance;

    for (int i = 0; i < maxRow; i++)
    {
        distance = get_distance(dataSet[i], testData);
        map_index_dis[i] = distance;
    }


}

void KNN::get_max_fre_label()
{
    vector<pair<int, double>> vec_index_dis(map_index_dis.begin(), map_index_dis.end());
    sort(vec_index_dis.begin(), vec_index_dis.end(), CmpByValue());
    cout << "前" << k << "个最小数据排序为:" << endl;
    for (int i = 0; i < k; i++)
    {
        cout << "index = " << vec_index_dis[i].first << " the distance= " << vec_index_dis[i].second
            << " the label = " << labels[vec_index_dis[i].first]
            << " the coordinate(" << dataSet[vec_index_dis[i].first][0] << ","
            << dataSet[vec_index_dis[i].first][0] << ")" << endl;

        map_label[labels[vec_index_dis[i].first]]++;
    }
    map<char, int>::iterator itr = map_label.begin();
    int max_freq = 0;
    char label;
    while (itr != map_label.end())
    {
        if (itr->second > max_freq)
        {
            max_freq = itr->second;
            label = itr->first;
        }
        itr++;
    }
    cout << "数据属于标签：" << endl;
    cout << "label = " << label << endl;
    QString result=label;
    qDebug()<<label;
    QSqlQueryModel *model=new QSqlQueryModel;
    model->setQuery("update knn set result='"+result+"' where name='function'");
}
//int main()
//{

//	KNN knn;
//	knn.get_all_distance();
//	knn.show();
//	knn.get_max_fre_label();

//	fin.close();
//	system("pause");
//	return 0;
//}
